package com.qiyuexinxi.chat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiyuexinxi.chat.domain.PictureInfo;
import com.qiyuexinxi.chat.domain.User;
import com.qiyuexinxi.chat.dto.request.GetUserInfoRequest;
import com.qiyuexinxi.chat.dto.request.UpdateUserRequest;
import com.qiyuexinxi.chat.dto.request.UserAddRequest;
import com.qiyuexinxi.chat.dto.response.GetUserInfoResponse;
import com.qiyuexinxi.chat.dto.vo.UserInfoVo;
import com.qiyuexinxi.chat.exception.reg.exception.BizErrorCodeEnum;
import com.qiyuexinxi.chat.exception.reg.exception.BizException;
import com.qiyuexinxi.chat.mapper.AttentionMapper;
import com.qiyuexinxi.chat.mapper.PictureInfoMapper;
import com.qiyuexinxi.chat.mapper.UserMapper;
import com.qiyuexinxi.chat.service.UserService;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * @author yangxingyu
 * @date 2020/2/26
 * @description
 */
@Service
public class UserServiceImpl implements UserService {

    @Value("${web.max-file-size}")
    private Integer maxFileSize;
    @Autowired
    UserMapper userMapper;
    @Autowired
    FileServiceImpl fileService;
    @Autowired
    PictureInfoMapper pictureInfoMapper;
    @Autowired
    AttentionMapper attentionMapper;

    @Override
    public boolean addUser(UserAddRequest userAddRequest) {
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        int i = userMapper.insertSelective(user);
        if (i > 0) {
            return true;
        }
        return false;
    }

    @Override
    public JSONObject fileUpload(Integer userId, Integer pictureType, MultipartFile pictureImg) {
        if (pictureImg.isEmpty()) {
            throw new BizException(BizErrorCodeEnum.PICTURE_IMG_EMPTY);
        }
        //校验文件大小
        Long size = pictureImg.getSize() / 1024 / 1024;
        if (size > maxFileSize) {
            throw new BizException(BizErrorCodeEnum.PICTURE_IMG_SIZE_ERROR);
        }
        String imagePath = fileService.fileUpload(pictureImg);
        PictureInfo pictureInfo = new PictureInfo();
        pictureInfo.setUserId(userId);
        pictureInfo.setPictureType(pictureType);
        pictureInfo.setPictureUrl(imagePath);
        int i = pictureInfoMapper.insertSelective(pictureInfo);
        if (i <= 0) {
            throw new BizException(BizErrorCodeEnum.PICTURE_IMG_INFO_FAILED);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pictureId", pictureInfo.getPictureId());
        jsonObject.put("imagePath", imagePath);
        return jsonObject;
    }

    @Override
    public List<GetUserInfoResponse> getUserInfo(GetUserInfoRequest getUserInfoRequest) {
        List<Integer> userIds = getUserInfoRequest.getUserIds();
        if (userIds == null || userIds.size() == 0) {
            return new ArrayList<GetUserInfoResponse>();
        }
        List<User> users = userMapper.selectByUserIds(getUserInfoRequest.getUserIds());
        List<GetUserInfoResponse> getUserInfoResponses = new ArrayList<GetUserInfoResponse>();
        for (User user : users) {
            getUserInfoResponses.add(manageUserInfo(user));
        }
        return getUserInfoResponses;
    }

    @Override
    public boolean updateUserInfo(UpdateUserRequest updateUserRequest) {
        User user = new User();
        BeanUtils.copyProperties(updateUserRequest, user);
        user.setBackPicture(updateUserRequest.getBackPicture() + "");
        user.setPictureUrls(JSON.toJSONString(updateUserRequest.getPictureUrls()));
        int i = this.userMapper.updateByPrimaryKeySelective(user);
        if (i <= 0) {
            throw new BizException(BizErrorCodeEnum.UPDATE_USER_INFO_FAILED);
        }
        return true;
    }

    /**
     * 根据用户id获取基本信息
     *
     * @param userId
     * @return
     */
    @Override
    public GetUserInfoResponse getUserInfoVo(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user != null && user.getDeleted() == 1) {
            return manageUserInfo(user);
        }
        return null;
    }

    @Override
    public UserInfoVo getUserBaseInfoVo(Integer userId) {
        List<UserInfoVo> userInfoVos = new ArrayList<UserInfoVo>();
        User user = userMapper.selectByPrimaryKey(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(user, userInfoVo);
        List<Integer> pictureList = JSON.parseArray(user.getPictureUrls(), Integer.class);
        if (pictureList != null && pictureList.size() > 0) {
            List<PictureInfo> pictureInfos = this.pictureInfoMapper.selectByUserId(pictureList);
            if (pictureInfos != null && pictureInfos.size() > 0) {
                userInfoVo.setPicture(pictureInfos.get(0).getPictureUrl());
            }
        }
        return userInfoVo;
    }


    private GetUserInfoResponse manageUserInfo(User user) {
        GetUserInfoResponse getUserInfoResponse = new GetUserInfoResponse();
        BeanUtils.copyProperties(user, getUserInfoResponse);
        //处理用户城市信息
        getUserInfoResponse.setCity(user.getCity());
        //处理用户图片信息
        getUserInfoResponse.setBackPicture(getBackPicture(user.getBackPicture()));
        getUserInfoResponse.setPictureUrls(getPictureUrls(user.getPictureUrls()));
        return getUserInfoResponse;
    }


    //获取用户信息图片
    public List<Map<String, Object>> getPictureUrls(String pictureUrls) {
        List pictureList = null;
        try {
            pictureList = JSON.parseArray(pictureUrls, Integer.class);
            if (pictureList == null || pictureList.size()==0) {
                pictureList = new ArrayList();
                pictureList.add("-1");
            }
        } catch (Exception e) {
            System.out.println("类型转换异常");
        }
        List pictureUrlsList = new ArrayList();
        List<PictureInfo> pictureInfos = pictureInfoMapper.selectByUserId(pictureList);
        for (PictureInfo pictureInfo : pictureInfos) {
            Map pInfo = new HashMap();
            pInfo.put("pictureId", pictureInfo.getPictureId());
            pInfo.put("pictureUrl", pictureInfo.getPictureUrl());
            pictureUrlsList.add(pInfo);
        }
        return pictureUrlsList;

    }

    //获取背景图片信息
    public Map<String, Object> getBackPicture(String backPicture) {
        if(backPicture==null || backPicture.length()==0){
            return null;
        }
        PictureInfo pictureInfo = pictureInfoMapper.selectByPrimaryKey(Integer.valueOf(backPicture));
        Map pInfo = new HashMap();
        pInfo.put("pictureId", pictureInfo.getPictureId());
        pInfo.put("pictureUrl", pictureInfo.getPictureUrl());
        return pInfo;
    }
}
